/**=========================================================
 * Directive: echarts.js
 * Initializes the echarts plugin and handles data refresh
 =========================================================*/

App.directive('echarts', ["$timeout", 'Utils',
    function($timeout, utils) {
        'use strict';
        
        return {
            restrict: 'EA',
            scope: {
                option: '='
            },
            link: function($scope, $element, $attrs){
                //解决ngDialog中无法显示的问题
                $timeout(function(){    
                    var myChart = echarts.init($element[0],'echartsTheme');

                    //自适应
                    window.addEventListener("resize", function () {
                        myChart.resize();
                    });
                    
                    var name = utils.isEmpty($attrs.name) ? 'chart' : $attrs.name,
                        level = utils.isEmpty($attrs.level) ? 1 : parseInt($attrs.level),
                        scope = $scope;
                    
                    //找到页面的scope
                    for (var i = 0; i < level; i++){
                        scope = scope['$parent'];
                    }
                    
                    //初始化
                    if (!utils.isEmpty($attrs.option)){
                        var optionPath = $attrs.option.split(".");
                        var option = scope;
                        for (var i = 0; i < optionPath.length; i++){
                            option = option[optionPath[i]];
                            if (utils.isEmpty(option)) break;
                        }
                        if (!utils.isEmpty(option)){
                            myChart.setOption(option,true);
                        }
                    }
                    
                    scope[utils.isEmpty($attrs.name) ? 'chart' : $attrs.name] = myChart;
                    
                    //监听option变化
                    $scope.$watch("option", 
                        function (newVal, oldVal) {
                            if (!utils.isEmpty(newVal) && newVal != oldVal){
                                myChart.setOption(newVal,true);
                                myChart.hideLoading();
                            }
                        }
                    );
                })
            }
        };
    }
]);
